<template>
  <basic-card style="height: 100%;width: 100%;box-sizing: border-box;" :hoverMove="hoverMove" :hovered="hovered"
              :borderLighting="false"
              :radius="true"
              :padding="false" :title="(goodInfo!=null&&goodInfo.lessIntro!=null)?goodInfo.lessIntro:''">
    <div style="width: 100%;border-radius: 0.8em;position: relative;padding: 10px;box-sizing: border-box"
         v-if="goodInfo.mainImage!=null">
      <div>
        <span @touchstart="touchState.start()"
              @touchend="touchState.cancel()" :class="[...touchState.classes]" @click.stop="toChangeStarState"
              class="good-card-star-outer">
          <HeartFilled v-if="isStar" class="good-card-star"/>
          <HeartOutlined v-else class="good-card-star"/>
        </span>

        <div class="img-box">
          <div class="img-box-inside">
            <img style="width: 100%;border-radius: 0.8em;vertical-align: top"
                 :src="goodInfo.mainImage">
          </div>
        </div>
        <span class="good-card-sale-point" v-if="isDiscount">
          Sale
        </span>

      </div>
    </div>
    <div class="zqazqazqa" style="padding: 7px 12px;line-height: 1.2;margin-bottom: 15px" v-if="showWord">
      <div class="good-card-title-font">
        {{ goodInfo.name }}

        <div v-if="goodInfo.producer!=null" style="padding: 5px 0;color: #646266;">
          by&nbsp;{{ goodInfo.producer }}
        </div>

      </div>
      <div class="good-card-pricing-outer">
        <div style="display: inline-block" v-if="isDiscount">
          <div class="good-card-pricing on-sale-old">
            {{ price }}
          </div>
          <div class="good-card-pricing-now on-sale-now">
            {{ nowPrice }}
          </div>

        </div>
        <div style="display: inline-block" v-else>
          <div class="good-card-pricing-now">
            {{ nowPrice }}
          </div>
        </div>
        <div>
          <a-tooltip color="white" :visible="showTooltipState" placement="top" @visibleChange="visibleChange"
                     :arrowPointAtCenter="true"
                     :overlayStyle="{width:'auto','max-width':'calc(100vw - 20px)','padding':'0 5px 8px 5px','z-index':'996'}"
                     :destroyTooltipOnHide="true"
          >
            <template #title>
              <div style="color: black;width: auto;padding: 5px;">
                <tbody>
                <tr v-for="specification in goodInfo.specificationList" style="display: table-row;">
                  <td style="vertical-align: top;">
                    <div class="good-list-font" style="margin-right: 5px;">
                      {{ specification.attributeKey }}
                    </div>
                  </td>
                  <td>
                    <div>
                      <a-radio-group name="primary_type"
                                     v-model:value="preToAddToCartState.specification[specification.id]"
                                     @change="changeSelection">
                        <a-radio v-for="attributeValue in specification.attributeValueList"
                                 :value="attributeValue.id">
                          <div class="good-list-font">
                            {{ attributeValue.attributeValue }}
                          </div>
                        </a-radio>
                      </a-radio-group>
                    </div>
                  </td>
                </tr>
                </tbody>

                <div
                    style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: space-between;align-items: center;border-top: 1px solid #eeeeee ;padding: 10px 3px 3px 3px;">
                  <div style="font-size: 18px;padding: 0 5px 0 0;white-space: nowrap;"
                       v-if="isAllSelected&&selectedSpecification!=null">
                    $ {{ selectedSpecification.price }}
                  </div>
                  <div style="font-size: 15px;padding: 0 5px 0 0;white-space: nowrap;"
                       v-if="isAllSelected&&selectedSpecification==null">
                    The product is not available.
                  </div>
                  <div style="font-size: 15px;padding: 0 5px 0 0;white-space: nowrap;" v-if="!isAllSelected">
                    Please select a specification
                  </div>
                  <div
                      style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-end;align-items: center;">
                    <basic-button @click="toSubmit" :under-line="false" :inverseColor="true"
                                  style="border:1px solid #1677ff;text-align: center;width: auto;height: 34px;transform: scale(1);margin-left: 10px;padding: 8px 10px;">
                  <span style="word-wrap: unset;white-space:nowrap;">
                    Add to Cart
                  </span>
                    </basic-button>
                  </div>
                </div>

              </div>
            </template>
            <img @click.stop="preToAddToCart" :src="shopCartIcon" class="good-card-pricing-icon" title="Add to Cart">
          </a-tooltip>
        </div>

      </div>
      <div class="good-card-add-button-outer" v-if="showAddButton">

        <!--        <div class="good-card-add-button">-->
        <!--          <div-->
        <!--              style="display: flex;flex-direction: column;flex-wrap: nowrap;align-content: center;justify-content: flex-start;align-items: center;">-->
        <!--            <a-tooltip color="white" :visible="showTooltipState" placement="top" @visibleChange="visibleChange"-->
        <!--                       :arrowPointAtCenter="true"-->
        <!--                       :overlayStyle="{width:'auto','max-width':'calc(100vw - 20px)','padding':'0 5px 8px 5px','z-index':'996'}"-->
        <!--                       :destroyTooltipOnHide="true"-->
        <!--                       :mouseLeaveDelay="0">-->
        <!--              <template #title>-->
        <!--                <div style="color: black;width: auto;padding: 5px;">-->
        <!--                  <tbody>-->
        <!--                  <tr v-for="specification in goodInfo.specificationList" style="display: table-row;">-->
        <!--                    <td style="vertical-align: top;">-->
        <!--                      <div class="good-list-font" style="margin-right: 5px;">-->
        <!--                        {{ specification.attributeKey }}-->
        <!--                      </div>-->
        <!--                    </td>-->
        <!--                    <td>-->
        <!--                      <div>-->
        <!--                        <a-radio-group name="primary_type"-->
        <!--                                       v-model:value="preToAddToCartState.specification[specification.id]"-->
        <!--                                       @change="changeSelection">-->
        <!--                          <a-radio v-for="attributeValue in specification.attributeValueList"-->
        <!--                                   :value="attributeValue.id">-->
        <!--                            <div class="good-list-font">-->
        <!--                              {{ attributeValue.attributeValue }}-->
        <!--                            </div>-->
        <!--                          </a-radio>-->
        <!--                        </a-radio-group>-->
        <!--                      </div>-->
        <!--                    </td>-->
        <!--                  </tr>-->
        <!--                  </tbody>-->

        <!--                  <div-->
        <!--                      style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: space-between;align-items: center;border-top: 1px solid #eeeeee ;padding: 10px 3px 3px 3px;">-->
        <!--                    <div style="font-size: 18px;padding: 0 5px 0 0;" v-if="isAllSelected&&selectedSpecification!=null">-->
        <!--                      $ {{ selectedSpecification.price }}-->
        <!--                    </div>-->
        <!--                    <div style="font-size: 15px;padding: 0 5px 0 0;" v-if="isAllSelected&&selectedSpecification==null">-->
        <!--                      暂无该型号产品-->
        <!--                    </div>-->
        <!--                    <div style="font-size: 15px;padding: 0 5px 0 0;" v-if="!isAllSelected">-->
        <!--                      请选择规格-->
        <!--                    </div>-->
        <!--                    <div-->
        <!--                        style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-end;align-items: center;">-->
        <!--                      <basic-button @click="toSubmit" :under-line="false" :inverseColor="true"-->
        <!--                                    style="border:1px solid #1677ff;text-align: center;width: auto;height: 34px;transform: scale(1);margin-left: 10px;padding: 8px 10px;">-->
        <!--                  <span style="word-wrap: unset;white-space:nowrap;">-->
        <!--                    Add to Cart-->
        <!--                  </span>-->
        <!--                      </basic-button>-->
        <!--                    </div>-->
        <!--                  </div>-->

        <!--                </div>-->
        <!--              </template>-->
        <!--            </a-tooltip>-->
        <!--            <basic-button @click.stop="preToAddToCart" :under-line="false"-->
        <!--                          style="border:1px solid #1677ff;text-align: center;width: 100%;height: 44px;transform: scale(1);background-color: white!important;">-->
        <!--              <span style="font-size: 16px;line-height: 1;">加入购物车</span>-->
        <!--            </basic-button>-->
        <!--          </div>-->

        <!--          <a-modal v-model:visible="preToAddToCartState.showModal" v-if="false" :closable="false">-->
        <!--            <table>-->
        <!--              <tbody>-->
        <!--              <tr v-for="specification in goodInfo.specificationList" style="display: table-row;">-->
        <!--                <td style="vertical-align: top;">-->
        <!--                  <div class="good-list-font">-->
        <!--                    {{ specification.attributeKey }}-->
        <!--                  </div>-->
        <!--                </td>-->
        <!--                <td>-->
        <!--                  <div>-->
        <!--                    <a-radio-group name="primary_type"-->
        <!--                                   v-model:value="preToAddToCartState.specification[specification.id]"-->
        <!--                                   @change="changeSelection">-->
        <!--                      <a-radio v-for="attributeValue in specification.attributeValueList"-->
        <!--                               :value="attributeValue.id">-->
        <!--                        <div class="good-list-font">-->
        <!--                          {{ attributeValue.attributeValue }}-->
        <!--                        </div>-->
        <!--                      </a-radio>-->
        <!--                    </a-radio-group>-->
        <!--                  </div>-->
        <!--                </td>-->
        <!--              </tr>-->
        <!--              </tbody>-->
        <!--            </table>-->
        <!--            <template #footer>-->
        <!--              <div-->
        <!--                  style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: space-between;align-items: center;">-->
        <!--                <div style="font-size: 18px;" v-if="isAllSelected&&selectedSpecification!=null">-->
        <!--                  $ {{ selectedSpecification.price }}-->
        <!--                </div>-->
        <!--                <div style="font-size: 15px;" v-if="isAllSelected&&selectedSpecification==null">-->
        <!--                  暂无该型号产品-->
        <!--                </div>-->
        <!--                <div style="font-size: 15px;" v-if="!isAllSelected">-->
        <!--                  请选择规格-->
        <!--                </div>-->
        <!--                <div-->
        <!--                    style="display: flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: flex-end;align-items: center;">-->
        <!--                  <basic-button @click="preToAddToCartState.showModal=false" :under-line="false"-->
        <!--                                style="border:1px solid #1677ff;text-align: center;width: 100%;height: 40px;transform: scale(1);background-color: white!important;">-->
        <!--                  <span style="word-wrap: unset;white-space:nowrap;">-->
        <!--                    Cancel-->
        <!--                  </span>-->
        <!--                  </basic-button>-->
        <!--                  <basic-button @click="toSubmit" :under-line="false" :inverseColor="true"-->
        <!--                                style="border:1px solid #1677ff;text-align: center;width: auto;height: 40px;transform: scale(1);margin-left: 10px;">-->
        <!--                  <span style="word-wrap: unset;white-space:nowrap;">-->
        <!--                    Add to Cart-->
        <!--                  </span>-->
        <!--                  </basic-button>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--            </template>-->
        <!--          </a-modal>-->
        <!--        </div>-->
      </div>
    </div>

  </basic-card>
</template>

<script>
import {defineComponent, ref, reactive, computed, watch, onMounted} from "vue";
import {useRouter} from 'vue-router'
import {isPhone} from "../../utils/isPhone";
import * as accounting from 'accounting'
import {HeartOutlined, HeartFilled} from '@ant-design/icons-vue';
import {addFavorite, deleteFavorite} from "../../api/FavoriteRequest";
import {notification} from "ant-design-vue";
import {searchGoodById, searchGoodSpecificationInfo} from "../../api/GoodRequest";
import {addCart} from "../../api/CartRequest";
import {useStore} from "vuex";
import shopCartIcon from '../../assets/img/icon/e389ce3d756104b9e8ab6c4ed5d74b8.png'

export default defineComponent({
  name: "good-card",
  props: {
    goodInfo: {
      default: null,
      validator(val) {
        return val != null;

      }
    },
    showWord: {
      default: true
    },
    showAddButton: {
      default: true
    },
    canShowTooltip: {
      default: true
    },
    hoverMove: {
      default: false
    },
    hovered: {
      default: 'auto'
    }
  },
  components: {
    HeartOutlined,
    HeartFilled
  },
  setup(props, context) {

    const store = useStore();
    const showWord = computed(() => props.showWord)

    const goodInfo = ref(props.goodInfo);
    const goodsSpecifications = ref(null);

    // const isDiscount = computed(() => (goodInfo.value.fakePrice != null && goodInfo.value.fakePrice > goodInfo.value.price));
    const isDiscount = false;

    const isStar = computed(() => goodInfo.value.favorite);
    const id = computed(() => goodInfo.value.id);

    const price = computed(() => {
      return accounting.formatMoney(goodInfo.value.fakePrice).replace(/(0+)$/g, "").replace(/(\.+)$/g, "")
    });
    const nowPrice = computed(() => {
      return accounting.formatMoney(goodInfo.value.price).replace(/(0+)$/g, "").replace(/(\.+)$/g, "")
    });
    const router = useRouter();

    const toChangeStarState = async () => {
      //todo 发出一个收藏/取消收藏的请求
      if (goodInfo.value.favorite) {
        goodInfo.value.favorite = false
        await deleteFavorite(goodInfo.value.id).then(res => {
          goodInfo.value.favorite = false
          notification.success({
            message: 'Cancel collection successfully'
          })
        }).catch((res) => {
          notification.warning({
            message: res.data.message
          })
        })

      } else {

        await addFavorite(goodInfo.value.id).then(res => {
          goodInfo.value.favorite = true
          notification.success({
            message: 'Collection successful'
          })
        }).catch((res) => {
          notification.warning({
            message: res.data.message
          })
        })
      }

    }
    const touchState = reactive({
      classes: isPhone() ? [] : ['good-card-star-outer-can-hover'],
      start() {
        if (isPhone()) {
          touchState.classes.push('good-card-star-outer-hover-isPhone');
        }
      },
      cancel() {
        if (isPhone()) {
          touchState.classes = [];
        }
      }
    })


    const preToAddToCart = async () => {
      await searchGoodById(id.value).then((res) => {
        res.data.result.goods[0].favorite = res.data.result.isFavorite
        goodInfo.value = res.data.result.goods[0]
      })
      if (!singleSpecification.value) {
        preToAddToCartState.showModal = true;
        context.emit("show-tooltip", id.value)

        for (let i = 0; i < goodInfo.value.specificationList.length; i++) {
          if (goodInfo.value.specificationList[i].attributeValueList != null && goodInfo.value.specificationList[i].attributeValueList.length > 0) preToAddToCartState.specification[goodInfo.value.specificationList[i].id] = goodInfo.value.specificationList[i].attributeValueList[0].id;
        }
        await changeSelection();
      } else {
        preToAddToCartState.showModal = false;
        context.emit("show-tooltip", id.value)

        preToAddToCartState.specification[goodInfo.value.specificationList[0].id] = goodInfo.value.specificationList[0].attributeValueList[0].id;
        await changeSelection();
        console.log(selectedSpecification.value);
        await toSubmit();
      }
    }

    const showTooltipState = computed(() => {
      return props.canShowTooltip && preToAddToCartState.showModal;
    })

    const preToAddToCartState = reactive({
      showModal: false,
      specification: {}
    })

    watch(preToAddToCartState.showModal, (nval) => {
      if (nval == false) {
        toCloseTooltip();
      }
    })

    const selectedSpecification = ref();

    const isAllSelected = computed(() => {
      if (goodInfo.value == null) return false
      if (goodInfo.value.specificationList == null) return false
      for (let i = 0; i < goodInfo.value.specificationList.length; i++) {
        if (preToAddToCartState.specification[goodInfo.value.specificationList[i].id] == null || preToAddToCartState.specification[goodInfo.value.specificationList[i].id] === undefined) {
          return false;
        }
      }
      return true
    })
    const singleSpecification = computed(() => {
      return goodInfo.value != null &&
          goodInfo.value.specificationList != null &&
          goodInfo.value.specificationList.length === 1 &&
          goodInfo.value.specificationList[0].attributeValueList != null &&
          goodInfo.value.specificationList[0].attributeValueList.length === 1;
    })

    const changeSelection =async () => {
      if (goodInfo.value == null) return;
      if (!isAllSelected.value) return;

      let data = []
      for (let specificationKey in preToAddToCartState.specification) {
        data.push({
          key: specificationKey,
          value: preToAddToCartState.specification[specificationKey]
        })
      }
      await searchGoodSpecificationInfo(data).then((res) => {
        if (res.data.result == null) {
          selectedSpecification.value = null;
          return;
        } else {
          res.data.result.GoodsSpecification.numPriceList = res.data.result.numPriceList
          selectedSpecification.value = res.data.result.GoodsSpecification;
        }
      })
    }
    const toSubmit = async () => {
      if (selectedSpecification.value == null) {
        if (isAllSelected) {
          notification.warning({
            message: 'No products of current model'
          })
        } else {
          notification.warning({
            message: 'Please select the type.'
          })
        }

        return;
      }
      await addCart({
        goodId: selectedSpecification.value.goodsId,
        specificationId: selectedSpecification.value.id,
        number: 1
      }).then((res) => {
        if (res.data.result != undefined && res.data.result.cartList != null) {
          for (let i = 0; i < res.data.result.cartList.length; i++) {
            //@ts-ignored
            res.data.result.cartList[i].good.specification.specification = JSON.parse(res.data.result.cartList[i].good.specification.specification)
          }
        }
        store.commit('SET_GLOBAL_INFO', {
          cartInfo: res.data.result
        })
        notification.success({
          message: 'Added successfully'
        })
        preToAddToCartState.showModal = false;
      }).catch((res) => {
        notification.warn({
          message: res.data.message,

        })
      })

    }

    const toCloseTooltip = () => {
      preToAddToCartState.showModal = false
      context.emit("show-tooltip", null)
    }

    const visibleChange = (e) => {
      if (e == false) {
        toCloseTooltip();
      }
    }

    return {
      visibleChange,
      toCloseTooltip,
      showTooltipState,
      touchState,
      changeSelection,
      preToAddToCartState,
      selectedSpecification,
      preToAddToCart,
      goodInfo,
      isDiscount,
      price,
      nowPrice,
      toSubmit,
      isStar,
      toChangeStarState,
      showWord,
      goodsSpecifications,
      isAllSelected,
      shopCartIcon
    }
  }
})
</script>

<style scoped lang="less">
.good-card-title-font {
  line-height: 1.2;
  font-size: 20px;
  font-weight: 400;
  word-break: break-all;
  transition: font-size, line-height, height .32s cubic-bezier(.22, .61, .36, 1);

  @media screen and (max-width: 992px) {
    font-size: 14px;
  }
  @media screen and (max-width: 768px) {
    font-size: 16px;
  }
}

.good-card-pricing-outer {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: space-between;
  align-items: center;

  .good-card-pricing-icon {
    object-fit: contain;
    box-sizing: border-box;
    width: 30px;
    height: 30px;
    margin-right: 5px;

  }
}

.good-card-pricing-now {
  //display: inline-block;
  font-size: 32px;

}

.on-sale-now {
  color: #c4113f;
  margin-right: 3px;
}

.on-sale-old {
  text-decoration: line-through;
  color: #646266;
}

.good-card-pricing {
  padding-top: 3px;
  //display: inline-block;
  font-size: 24px;
}

@media screen and (max-width: 576px) {
  .good-card-pricing-now {
    font-size: 20px;
  }

  .good-card-pricing {
    font-size: 14px;
  }
}

.good-card-star-outer {
  position: absolute;
  background-color: white;
  line-height: 0;
  font-size: 0;
  transition: all .18s cubic-bezier(.22, .61, .36, 1);
  z-index: 100;
  border: 1px solid #dfdfe1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

  * {
    transition: all .18s cubic-bezier(.22, .61, .36, 1);
  }

  .good-card-star {
    color: #1677ff
  }

  @media screen and (max-width: 768px) {
    border-radius: 14px;
    width: 28px;
    height: 28px;
    .good-card-star {
      //margin: 3px;
      font-size: 20px;
    }

    right: 15px;
    top: 15px;
  }
  //@media screen and (max-width: 576px) {
  //  border-radius: 14px;
  //  width: 24px;
  //  height: 24px;
  //  .good-card-star {
  //    //margin: 4px;
  //    font-size: 16px;
  //  }
  //
  //  right: 8px;
  //  top: 8px;
  //}
  @media screen and (min-width: 768px) {
    border-radius: 16px;
    width: 32px;
    height: 32px;

    right: 20px;
    top: 20px;
    .good-card-star {
      //margin: 5px;
      font-size: 22px;
    }
  }
}

.good-card-star-outer-hover {
  background-color: #1677ff !important;

  .good-card-star {
    color: white !important;
  }
}

.good-card-star-outer-can-hover {
}

.good-card-star-outer-can-hover:hover {
  background-color: #1677ff !important;

  .good-card-star {
    color: white !important;
  }
}

.good-card-star-outer-hover-isPhone {
  background-color: #1677ff !important;

  .good-card-star {
    color: white !important;
  }
}

.good-card-sale-point {
  background-color: #c4113f;
  border-bottom-left-radius: 0.8em;
  border-top-right-radius: 0.8em;
  position: absolute;
  left: 10px;
  bottom: 10px;
  padding: 5px 8px;

  @media screen and (max-width: 768px) {
    font-size: 12px;
  }
  @media screen and (min-width: 768px) {
    font-size: 14px;
  }


  color: white;
}

.img-box {
  height: 0;
  width: 100%;

  padding-bottom: 100%;
  position: relative;

  .img-box-inside {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: space-around;
    align-items: center;
  }
}

.good-card-add-button-outer {
  height: 10px;
  position: relative;

  .good-card-add-button {
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
  }
}

.zqazqazqa {
  margin-top: 40px;
}

@media screen and (max-width: 768px) {
  .good-card-add-button-outer {
    height: 10px;
    position: relative;

  }

  .zqazqazqa {
    margin-top: 20px;
  }
}

.good-list-font {
  display: inline-block;
  font-size: 16px;
  white-space: nowrap;
  line-height: 31.2px;
  @media screen and (max-width: 768px) {
    font-size: 14px;
    line-height: 24.8px;
  }
  @media screen and (max-width: 576px) {
    font-size: 13px;
    line-height: 25.6px;
  }

}
</style>
